package com.loansystem.controller.admin;

import com.loansystem.bean.user.Loans;
import com.loansystem.bean.user.User;
import com.loansystem.bean.user.User_Loans_VO;
import com.loansystem.bean.user.User_Rule_VO;
import com.loansystem.service.admin.AdminService;
import com.loansystem.utils.ExcelUtil;
import com.loansystem.utils.FileUpload;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class AdminController {
    @Autowired
    AdminService adminService;

    //跳转查看申请状态页
    @RequestMapping("/admin/goLoansInfo")
    public String goLoansInfo() {
        return "admin/getLoansInfo";
    }
    //跳转用户管理页
    @RequestMapping("/admin/goUserInfo")
    public String goUserInfo() {
        return "admin/getUserInfo";
    }
    //获取个人信息
    @RequestMapping("/admin/userInfo")
    public String goUserInfo(Model model) {
        Subject subject = SecurityUtils.getSubject();
        User user = (User) subject.getPrincipal();
        model.addAttribute("user",user);
        return "admin/userInfo";
    }
    //获取贷款申请信息
    @RequestMapping("/admin/getLoansInfo")
    @ResponseBody
    public List<Map<String,Object>> getLoansInfo() {
        //获取用户的所有贷款提交信息
        List<User_Loans_VO> loansInfo = adminService.loansInfo();
        List<Map<String,Object>> resultList = new ArrayList<>();
        for (int i=0;i<loansInfo.size();i++){
            Map<String,Object> infoMap = new HashMap<>();
            Map<String,Object> imagesMap = new HashMap<>();
            infoMap.put("user_mail",loansInfo.get(i).getUser_mail());
            infoMap.put("user_name",loansInfo.get(i).getUser_name());
            infoMap.put("user_birthday",loansInfo.get(i).getUser_birthday());
            infoMap.put("id_card",loansInfo.get(i).getId_card());
            infoMap.put("user_sex",loansInfo.get(i).getUser_sex());
            infoMap.put("rand_card",loansInfo.get(i).getRand_card());
            infoMap.put("user_reputation",loansInfo.get(i).getUser_reputation());
            infoMap.put("Loans_id",loansInfo.get(i).getLoans_id());
            infoMap.put("Loans_money",loansInfo.get(i).getLoans_money());
            infoMap.put("Loans_purpose",loansInfo.get(i).getLoans_purpose());
            infoMap.put("Loans_date",loansInfo.get(i).getLoans_date());
            infoMap.put("Due_date",loansInfo.get(i).getDue_date());
            infoMap.put("loansState",loansInfo.get(i).getLoans_state());
            //设置状态, 设置前端tag标签的类型
            if(loansInfo.get(i).getLoans_state()==1){
                infoMap.put("Loans_state","申请已提交");
                infoMap.put("stateType","");
            }else if(loansInfo.get(i).getLoans_state()==2){
                infoMap.put("Loans_state","正在处理");
                infoMap.put("stateType","warning");
            }else if(loansInfo.get(i).getLoans_state()==3){
                infoMap.put("Loans_state","已完成");
                infoMap.put("stateType","success");
            }else if(loansInfo.get(i).getLoans_state()==4){
                infoMap.put("Loans_state","请求被驳回");
                infoMap.put("stateType","danger");
            }
            //设置文件
            if(loansInfo.get(i).getId_card_img()!=null){
                imagesMap.put("身份证正反面",loansInfo.get(i).getId_card_img());
            }
            if(loansInfo.get(i).getBill_img()!=null){
                imagesMap.put("近六个月的流水",loansInfo.get(i).getBill_img());
            }
            if(loansInfo.get(i).getCertificate_of_employment_img()!=null){
                imagesMap.put("工作证明",loansInfo.get(i).getCertificate_of_employment_img());
            }
            if(loansInfo.get(i).getCredit_report_img()!=null){
                imagesMap.put("征信报告",loansInfo.get(i).getCredit_report_img());
            }
            if(loansInfo.get(i).getHousing_ownership_certificate_img()!=null){
                imagesMap.put("房屋产权证",loansInfo.get(i).getHousing_ownership_certificate_img());
            }
            infoMap.put("fileImg",imagesMap);
            resultList.add(infoMap);
        }
        return resultList;
    }
    //修改业务状态
    @RequestMapping("/admin/updateLoansState")
    @ResponseBody
    public Boolean updateLoansState(@RequestParam("loans_id") Integer loans_id,@RequestParam("loans_state") Integer loans_state){
        System.out.println(loans_id);
        System.out.println(loans_state);
        int i = adminService.updateLoansState(loans_id, loans_state);
        if(i>0){
            return true;
        }
        return false;
    }
    //获取所有用户信息
    @RequestMapping("/admin/getUserInfo")
    @ResponseBody
    public List<User_Rule_VO> getUserInfo() {
        List<User_Rule_VO> users = adminService.userInfo();
        return users;
    }
    //获取所有用户信息
    @RequestMapping("/admin/searchUserInfo")
    @ResponseBody
    public List<User_Rule_VO> searchUserInfo(String user_mail,String user_name) {
        System.out.println(user_mail);
        System.out.println(user_name);
        user_mail = user_mail.trim();
        user_name = user_name.trim();
        List<User_Rule_VO> users = adminService.getUserInfo(user_mail,user_name);
        return users;
    }
    //删除用户信息
    @RequestMapping("/admin/delUserInfo")
    @ResponseBody
    public Boolean delUserInfo(Integer user_id) {
        int i = adminService.deleteUserInfo(user_id);
        if(i>0){
            return true;
        }
        return false;
    }
    //更新用户信息
    @RequestMapping("/admin/updateUserInfo")
    @ResponseBody
    public Boolean updateUserInfo(User user, MultipartFile imgFile) {
        System.out.println(user);
        if (imgFile != null) {
            //上传头像
            FileUpload.doSingleFileUpload(imgFile, "images/user", "userImg", user, "user_img");
        }
        if(user.getUser_id()==-1){
            System.out.println("添加用户");
            int i = adminService.addUserInfo(user);
            if (i > 0) {
                return true;
            }
        }else{
            int i = adminService.updateUserInfo(user);
            if (i > 0) {
                return true;
            }
        }
        return false;
    }

    //导出excel
    @RequestMapping("/admin/exportExcel")
    public void ExportExcel(HttpServletResponse response) {
        List<User_Rule_VO> users = adminService.userInfo();
        String[] title={"用户id","用户头像地址","用户账号","用户密码","用户昵称","出生日期","身份证号","性别","银行卡号","用户角色","用户状态","用户信誉度"};
        String[][] value = new String[users.size()][];
        User_Rule_VO[] data = new User_Rule_VO[users.size()];
        //查询是降序排列，这里逆序打印保持数据顺序
        int i = users.size()-1;
        for (User_Rule_VO user : users) {
            data[i--] = user;
        }

        for (int j = 0; j < data.length; j++) {
            User_Rule_VO user = data[j];
            value[j] = new String[]{String.valueOf(user.getUser_id()),user.getUser_img(),user.getUser_mail(),
                    user.getUser_pwd(),user.getUser_name(),user.getUser_birthday(),user.getId_card(),user.getUser_sex(),
                    user.getRand_card(),user.getRole_name(), String.valueOf(user.getUser_state()), String.valueOf(user.getUser_reputation())};
        }
        HSSFWorkbook wb = ExcelUtil.getHSSFWorkbook("userSheet", title, value, null);

        try {
            this.setResponseHeader(response, "userSheet.xls");
            OutputStream os = response.getOutputStream();
            wb.write(os);
            os.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                wb.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    //发送响应流方法
    public void setResponseHeader(HttpServletResponse response, String fileName) {
        try {
            try {
                fileName = new String(fileName.getBytes(),"ISO8859-1");
            } catch (UnsupportedEncodingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            response.setContentType("application/octet-stream;charset=ISO8859-1");
            response.setHeader("Content-Disposition", "attachment;filename="+ fileName);
            response.addHeader("Pargam", "no-cache");
            response.addHeader("Cache-Control", "no-cache");
        } catch (Exception ex) {
            ex.printStackTrace();
        }

    }
}
